<template>
  <div
    class="shorts-container"
    @mousedown="handleMouseDown"
    @mousemove="handleMouseMove"
    @mouseup="handleMouseUp"
    @mouseleave="handleMouseUp"
    @wheel="handleWheel"
    @touchstart="handleTouchStart"
    @touchmove="handleTouchMove"
    @touchend="handleTouchEnd"
  >
    <!-- 返回按钮 -->
    <div class="back-button" @click.stop="navigateTo('/')" @touchstart.stop="navigateTo('/')">
      <i class="i-carbon-arrow-left text-2xl"></i>
    </div>

    <!-- 取消静音按钮 -->
    <div v-if="isMuted" class="unmute-button" @click.stop="handleCancelMuted" @touchstart.stop="handleCancelMuted">
      <i class="i-carbon-volume-mute mr-2"></i>
      点击取消静音
    </div>

    <!-- 短视频列表 -->
    <div class="shorts-wrapper" :style="{ transform: `translateY(${offset}vh)` }">
      <div
        v-for="(short, index) in shorts"
        :key="short.shortId"
        class="short-item"
      >
        <!-- 播放按钮指示器 -->
        <div v-if="isShowPlayButton && index === currentIndex" class="play-button-indicator">
          <i class="i-carbon-play-filled text-6xl"></i>
        </div>

        <!-- 视频 -->
        <video
          :ref="el => setVideoRef(el, index)"
          class="short-video"
          :src="short.videoUrl"
          :poster="short.poster"
          :autoplay="index === 0"
          loop
          :muted="isMuted"
          preload="metadata"
          playsinline
          controlslist="nodownload"
        ></video>

        <!-- 视频信息 -->
        <div class="video-info">
          <h3 class="video-description">{{ short.description }}</h3>
        </div>

        <!-- 互动按钮 -->
        <ShortVideoActions
          :short="short"
          :initial-status="index === currentIndex ? currUserShortInfo : { isLike: false, isCollection: false }"
          @update:status="currUserShortInfo = $event"
        />
      </div>
    </div>

    <!-- 加载更多指示器 -->
    <div v-if="loading" class="loading-indicator">
      <el-icon class="is-loading" :size="40" color="#fff">
        <Loading />
      </el-icon>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Loading } from '@element-plus/icons-vue'

definePageMeta({
  layout: false
})

const userStore = useUserStore()
const { getShortUserStatus } = useShortActions()

// 状态
const currentIndex = ref(0)
const previousIndex = ref(0)
const isDragging = ref(false)
const startY = ref(0)
const offset = ref(0)
const threshold = 100
const isShowPlayButton = ref(false)
const shorts = ref<any[]>([])
const isMuted = ref(true)
const pageNum = ref(1)
const loading = ref(false)
const hasMore = ref(true)
const videoRefs = ref<HTMLVideoElement[]>([])
const currUserShortInfo = ref({
  isLike: false,
  isCollection: false
})

// 设置视频引用
const setVideoRef = (el: any, index: number) => {
  if (el) {
    videoRefs.value[index] = el
  }
}

// 当前短视频
const currentShort = computed(() => shorts.value[currentIndex.value])

// 监听当前短视频变化，获取用户状态
watch(
  () => currentShort.value,
  async (short) => {
    if (short && userStore.memberUserId) {
      const status = await getShortUserStatus(short.shortId)
      currUserShortInfo.value = { ...status }
    }
  }
)

// 获取短视频列表
const fetchShorts = async () => {
  if (loading.value || !hasMore.value) return

  loading.value = true
  try {
    const data: any = await $fetch('/dev-api/app/shorts/list', {
      params: {
        pageNum: pageNum.value,
        pageSize: 6
      }
    })

    // /app/** 接口返回 {rows: [], total: number}
    const newShorts = data.rows || []
    shorts.value = [...shorts.value, ...newShorts]

    if (newShorts.length < 6) {
      hasMore.value = false
    }
  } catch (error) {
    console.error('获取短视频列表失败:', error)
    // 如果 API 失败，使用模拟数据
    const mockShorts = Array.from({ length: 6 }, (_, i) => ({
      shortId: shorts.value.length + i + 1,
      videoUrl: `https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8`,
      poster: `https://via.placeholder.com/400x600?text=Short${shorts.value.length + i + 1}`,
      description: `这是第 ${shorts.value.length + i + 1} 个短视频的描述`,
      likes: Math.floor(Math.random() * 10000),
      collection: Math.floor(Math.random() * 1000),
      comments: Math.floor(Math.random() * 500),
      shareCount: Math.floor(Math.random() * 100),
      memberUser: {
        memberUserId: 1,
        avatar: 'https://via.placeholder.com/100',
        nickName: `用户${i + 1}`
      }
    }))
    shorts.value = [...shorts.value, ...mockShorts]
  } finally {
    loading.value = false
  }
}

// 滚动到指定短视频
const scrollToShort = async (index: number) => {
  if (isDragging.value) return

  offset.value = -index * 100

  if (previousIndex.value !== index) {
    isShowPlayButton.value = false

    // 暂停所有视频
    videoRefs.value.forEach((video, i) => {
      if (video) {
        if (i === index) {
          video.play().catch(() => {})
        } else {
          video.pause()
        }
      }
    })

    // 如果到达最后一个，加载更多
    if (index === shorts.value.length - 1 && hasMore.value) {
      pageNum.value++
      await fetchShorts()
    }
  } else {
    // 点击同一个视频，切换播放/暂停
    const currentVideo = videoRefs.value[currentIndex.value]
    if (currentVideo) {
      if (currentVideo.paused) {
        currentVideo.play().catch(() => {})
        isShowPlayButton.value = false
      } else {
        currentVideo.pause()
        isShowPlayButton.value = true
      }
    }
  }

  previousIndex.value = index
}

// 鼠标事件
const handleMouseDown = (event: MouseEvent) => {
  isDragging.value = true
  startY.value = event.clientY
}

const handleMouseMove = (event: MouseEvent) => {
  if (!isDragging.value) return
  const deltaY = event.clientY - startY.value
  offset.value = -currentIndex.value * 100 + (deltaY / window.innerHeight) * 100
}

const handleMouseUp = (event: MouseEvent) => {
  if (!isDragging.value) return
  isDragging.value = false

  const deltaY = event.clientY - startY.value
  if (deltaY < -threshold && currentIndex.value < shorts.value.length - 1) {
    currentIndex.value++
  } else if (deltaY > threshold && currentIndex.value > 0) {
    currentIndex.value--
  }

  scrollToShort(currentIndex.value)
}

// 滚轮事件
const handleWheel = (event: WheelEvent) => {
  const delta = event.deltaY
  if (delta > 0 && currentIndex.value < shorts.value.length - 1) {
    currentIndex.value++
    scrollToShort(currentIndex.value)
  } else if (delta < 0 && currentIndex.value > 0) {
    currentIndex.value--
    scrollToShort(currentIndex.value)
  }
}

// 触摸事件
const handleTouchStart = (event: TouchEvent) => {
  isDragging.value = true
  startY.value = event.touches[0].clientY
}

const handleTouchMove = (event: TouchEvent) => {
  if (!isDragging.value) return
  const deltaY = event.touches[0].clientY - startY.value
  offset.value = -currentIndex.value * 100 + (deltaY / window.innerHeight) * 100
}

const handleTouchEnd = (event: TouchEvent) => {
  if (!isDragging.value) return
  isDragging.value = false

  const deltaY = event.changedTouches[0].clientY - startY.value
  if (deltaY < -threshold && currentIndex.value < shorts.value.length - 1) {
    currentIndex.value++
  } else if (deltaY > threshold && currentIndex.value > 0) {
    currentIndex.value--
  }

  scrollToShort(currentIndex.value)
}

// 取消静音
const handleCancelMuted = () => {
  isMuted.value = false
  const currentVideo = videoRefs.value[currentIndex.value]
  if (currentVideo) {
    currentVideo.muted = false
    currentVideo.play().catch(() => {})
  }
}

// 初始化
onMounted(async () => {
  await fetchShorts()

  // 获取当前视频的用户状态
  if (currentShort.value && userStore.memberUserId) {
    const status = await getShortUserStatus(currentShort.value.shortId)
    currUserShortInfo.value = { ...status }
  }
})

// SEO
useSeoMeta({
  title: '短视频',
  description: '浏览精彩短视频内容'
})
</script>

<style scoped>
.shorts-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background-color: #000;
  z-index: 9999;
}

.back-button {
  position: absolute;
  top: 15px;
  left: 15px;
  z-index: 11;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  width: 40px;
  height: 40px;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  backdrop-filter: blur(10px);
}

.unmute-button {
  position: absolute;
  top: 15px;
  right: 15px;
  z-index: 11;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  padding: 8px 16px;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 20px;
  backdrop-filter: blur(10px);
  font-size: 14px;
}

.shorts-wrapper {
  transition: transform 0.3s ease-in-out;
  height: 100%;
}

.short-item {
  position: relative;
  width: 100vw;
  height: 100vh;
}

.short-video {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background-color: #000;
}

.play-button-indicator {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 5;
  opacity: 0.65;
  color: white;
  pointer-events: none;
}

.video-info {
  position: absolute;
  bottom: 100px;
  left: 15px;
  right: 80px;
  z-index: 10;
  color: white;
}

.video-description {
  font-size: 16px;
  line-height: 1.5;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.8);
}

.loading-indicator {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 11;
}
</style>
